package blackstar.agent.security;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import blackstar.agent.AgentConfig;

/**
 * @author RayWoo (ayufox@gmail.com)
 * 
 */
public class DefaultUserManager implements UserManager
{
	private final static Log LOGGER = LogFactory
			.getLog(DefaultUserManager.class);
	private Map<String, SecurityUser> securityUserMap = new HashMap<String, SecurityUser>();

	public DefaultUserManager() throws IOException
	{
		File configFile = new File(AgentConfig.getConfigPath() + File.separator
				+ "password.xml");
		if (!configFile.exists() || !configFile.isFile())
		{
			LOGGER.info("JMX Authentication Password File["
					+ configFile.getAbsolutePath() + "] not found");
			configFile = new File(AgentConfig.getConfigPath() + File.separator
					+ "password.properties");
			if (!configFile.exists() || !configFile.isFile())
			{
				LOGGER.info("JMX Authentication Password File["
						+ configFile.getAbsolutePath() + "] not found");
				throw new IllegalArgumentException("No password Config Found");
			}
		}

		Properties passwords = new Properties();
		InputStream is = null;
		try
		{
			is = new FileInputStream(configFile);
			if (configFile.getName().endsWith("xml"))
			{
				passwords.loadFromXML(is);
			} else
			{
				passwords.load(is);
			}
		} finally
		{
			if (is != null)
			{
				is.close();
			}
		}

		for (Map.Entry<Object, Object> entry : passwords.entrySet())
		{
			this.securityUserMap.put((String) entry.getKey(),
					new DefaultSecurityUser((String) entry.getKey(), (String)  entry.getValue()));
		}
	}

	public SecurityUser findUser(String username)
	{
		return this.securityUserMap.get(username);
	}

}
